﻿using inspf.Default;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace inspf.Hup
{
    /// <summary>
    /// EXCEL 帮助类文件
    /// </summary>
    public class XlsHup
    {
        /// <summary>
        /// 创建空XLS文件
        /// </summary>
        /// <param name="xlsname"></param>
        public static void CreateXlsChangeds(string xlsname, ObservableCollection<Goods> goods)
        {
            int i = 0, n = 0, j = 1;
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet");
            IRow row = sheet.CreateRow(sheet.LastRowNum);//在工作表中添加一行
            PropertyInfo[] peroperties = typeof(Goods).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in peroperties)
            {
                object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objs.Length > 0)
                {
                    row.CreateCell(i).SetCellValue(((DescriptionAttribute)objs[0]).Description);
                    i++;
                }
            }

            foreach (var gs in goods)
            {
                n = 0; row = sheet.CreateRow(j++);
                PropertyInfo[] gsp = gs.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo gspsub in gsp)
                {
                    row.CreateCell(n).SetCellValue(gspsub.GetValue(gs, null) == null ? "" : gspsub.GetValue(gs, null).ToString());
                    n++;
                }
            }
            workbook.Write(ms);//将Excel写入流
            ms.Flush();
            ms.Position = 0;
            FileStream dumpFile = new FileStream(xlsname, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            ms.WriteTo(dumpFile);//将流写入文件
            ms.Close();


        }
    }
}
